package domain;

import service.PromotionCalculate;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 购物车
 */
public class ShoppingCart {
    private ShoppingItem[] items;
    private PromotionCalculate promotionCalculate; // 促销计算

    public ShoppingCart(int itemCount) {
        items = new ShoppingItem[itemCount];
    }

    public void addItem(ShoppingItem item) {
        for (int i = 0; i < items.length; i++) {
            if (items[i] == null) {
                items[i] = item;
                break;
            }
        }
    }

    public ShoppingItem[] getItems() {
        return items;
    }

    public void setItems(ShoppingItem[] items) {
        this.items = items;
    }

    public PromotionCalculate getPromotionCalculate() {
        return promotionCalculate;
    }

    public void setPromotionCalculate(PromotionCalculate promotionCalculate) {
        this.promotionCalculate = promotionCalculate;
    }

    /**
     * 计算购物车中所有商品的总价
     * @return 商品总价
     */
    public BigDecimal calculateTotalPrice() {
        BigDecimal totalPrice = new BigDecimal("0");
        for (ShoppingItem item : items) {
            String fruitName = item.getFruits().getFruitName();
            if (item != null) {
                //应用促销策略
                if (promotionCalculate != null&&"折扣".equals(promotionCalculate.promotionName()) && "草莓".equals(fruitName)){
                    totalPrice = totalPrice.add(promotionCalculate.calculate(item.calculatePrice()));
                }else {
                    totalPrice = totalPrice.add(item.calculatePrice());
                }
            }
        }
        if (promotionCalculate != null&&"满减".equals(promotionCalculate.promotionName())){
            totalPrice = promotionCalculate.calculate(totalPrice);
        }

        return totalPrice.setScale(2, RoundingMode.HALF_UP);
    }
}
